package cn.daniellee.plugin.wc.storage;

import cn.daniellee.plugin.wc.Welcome;
import cn.daniellee.plugin.wc.model.PlayerData;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StorageConverter {

    private SqliteStorage sqliteStorage;

    private MysqlStorage mysqlStorage;

    public StorageConverter(SqliteStorage sqliteStorage, MysqlStorage mysqlStorage) {
        this.sqliteStorage = sqliteStorage;
        this.mysqlStorage = mysqlStorage;
    }

    // 只拷贝老玩家数据，欢迎数据丢弃（老玩家不会再被欢迎）
    public void execute() {
        String tablePrefix = Welcome.getInstance().getConfig().getString("storage.mysql.table-prefix", "wc_");
        Connection sqliteConn = sqliteStorage.getConnection();
        Connection mysqlConn = mysqlStorage.getConnection();
        // 查询所有玩家
        List<PlayerData> allPlayer = new ArrayList<>();
        String playerQuery = "SELECT `name`,`join_date` FROM `player`";
        try(Statement statement = sqliteConn.createStatement()){
            ResultSet resultSet = statement.executeQuery(playerQuery);
            while (resultSet.next()) {
                PlayerData playerData = new PlayerData(resultSet.getString("name"));
                playerData.setJoinDate(resultSet.getLong("join_date"));
                allPlayer.add(playerData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Welcome.getInstance().getLogger().info(" ");
            Welcome.getInstance().getLogger().info("[Welcome]An error occurred while trans Sqlite data to Mysql.".replace("&", "§"));
            Welcome.getInstance().getLogger().info(" ");
        }
        // 写入MySQL
        String playerInsert = "INSERT INTO `" + tablePrefix + "player` (`name`,`join_date`)VALUES(?,?)";
        PreparedStatement statement = null;
        try {
            // 关闭MySQL自动提交
            mysqlConn.setAutoCommit(false);
            statement = mysqlConn.prepareStatement(playerInsert);
            for (PlayerData playerData : allPlayer) {
                statement.clearBatch();
                statement.setString(1, playerData.getName());
                statement.setLong(2, playerData.getJoinDate());
                statement.addBatch();
            }
            statement.executeBatch();
            mysqlConn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            Welcome.getInstance().getLogger().info(" ");
            Welcome.getInstance().getLogger().info("[Welcome]An error occurred while trans Sqlite data to Mysql.".replace("&", "§"));
            Welcome.getInstance().getLogger().info(" ");
        } finally {
            try {
                mysqlConn.setAutoCommit(true);
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException ignored) {}
        }
    }

}
